import java.io.*;
import java.sql.*;
import javax.servlet.*;
import javax.servlet.http.*;

import db.DatabaseConnector;
import java.text.SimpleDateFormat;

public class ListQuestions extends HttpServlet {

//This subroutine is called by ListQuestions.jsp (admin page)
public void doGet(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {

	//The JSP document passes in which db table to use
	String tName = "questions";

	//Variables for the database connection
	DatabaseConnector con = new DatabaseConnector(DatabaseConnector.getDatabaseType());
	ResultSet rs = null;

	response.setContentType("text/html");
    	PrintWriter out = response.getWriter();

    try {
        String SQL = "SELECT ID, Date_Posted, Question, Response FROM " + tName + " WHERE ID > 1 ORDER BY Date_Posted DESC";
        rs = con.selectSQL_RS(SQL);
       
    	//Display the contents
        if(rs != null)
        {
            while(rs.next()) {
                String idString = rs.getString("ID");
		String dateString = new SimpleDateFormat("MM/dd/yyyy").format(rs.getObject("Date_Posted"));
		String questionString = rs.getString("Question");
		String responseString = rs.getString("Response");

		if(questionString.length() > 50) {
			questionString = questionString.substring(0, 50) + "...";
		}

    		out.print("<TR><TD>" + dateString);
    		out.print("</TD><TD> " + questionString);

		if(responseString!=null) {
    			out.print("</TD><TD><font color=\"009900\">Answered");
		} else {
    			out.print("</TD><TD><font color=\"ff0000\">Not Answered");
		}
    		out.println("</TD><TD><a href=\"EditQuestion.jsp?ID=" + idString + "\">Edit/Respond</a></td></tr>");
            }
      }
    } catch (SQLException e) {
	out.println("SQLException caught: " + e.getMessage());
    }finally {
    	try {
            if(rs != null) rs.close();
            if(con != null) con.CleanUp();
	}
	catch (SQLException ignored) {}        
    } 
}
}
